package com.demo.interceptor;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author zm
 */
@Slf4j
@Configuration
public class UserWebMvc implements WebMvcConfigurer {
    @Autowired
    private UserInterceptor userInterceptor;

    @Bean
    public CorsInterceptor getCorsInterceptor() {
        return new CorsInterceptor();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations("file:" + System.getProperty("user.home") + "/images/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 设置白名单，哪些接口不要token
     * 拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getCorsInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(userInterceptor).addPathPatterns("/**")
                //第一行为必要参数，少了报错
                .excludePathPatterns("/swagger-resources/**", "/swagger-ui.html/**", "/images/**", "/webjars/**", "/v2/**", "/error", "/", "/csrf")
                //添加自己不需要拦截的----接口
                .excludePathPatterns("/testToken").excludePathPatterns("/login/userLogin");

        log.info("自定义拦截器已启动.........");

    }

    /**
     * 视图控制器
     *
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/user").setViewName("user");
        registry.addViewController("/login").setViewName("login");
    }

}
